<template>
  <div class="app-container">
    <!-- 表格-条件筛区域  -->
    <div class="filter-container">
      <el-input placeholder="请输入题目内容" v-model="searchParam.SEARCH_LIKE_content" clearable style="width: 200px;"
                class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select clearable v-model="searchParam.SEARCH_EQ_subject_id" placeholder="请选择科目" class="filter-item">
        <el-option v-for="item in subjectList" :key="item.id" :label="item.levelName" :value="item.id"></el-option>
      </el-select>
      <el-select clearable v-model="searchParam.SEARCH_EQ_base_id" placeholder="请选择题库" class="filter-item">
        <el-option v-for="item in baseList" :key="item.id" :label="item.baseName" :value="item.id"></el-option>
      </el-select>
      <el-select clearable class="filter-item" v-model="searchParam.SEARCH_EQ_difficult" placeholder="请选择难度系数">
        <el-option label="1分" :value="1"></el-option>
        <el-option label="2分" :value="2"></el-option>
        <el-option label="3分" :value="3"></el-option>
        <el-option label="4分" :value="4"></el-option>
        <el-option label="5分" :value="5"></el-option>
      </el-select>
      <el-select clearable class="filter-item" v-model="searchParam.SEARCH_EQ_question_type" placeholder="请选择题型">
        <el-option label="单选题" :value="1"></el-option>
        <el-option label="多选题" :value="2"></el-option>
        <el-option label="判断题" :value="3"></el-option>
        <el-option label="填空题" :value="4"></el-option>
        <el-option label="实践题" :value="6"></el-option>
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus"
                 @click="handleCreate"> 新增
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-plus"
                 @click="handleImport"> 导入考题
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-plus"
                 @click="handleExport"> 导出模板
      </el-button>
    </div>

    <!-- 表格-内容区域 -->
    <el-table v-loading="listLoading" :key="tableKey" :data="tableList" border fit highlight-current-row
              style="width: 100%;">
      <el-table-column v-for="column in columns" :key="column.prop"
                       :prop="column.prop"
                       :label="column.label"
                       :width="column.width"
                       :align="column.align?column.align:'center'"
                       :min-width="column.minWidth"
                       :sortable="column.sortable"
                       :fixed="column.fixed"
                       :type="column.type" :formatter="column.formatter">
        <template slot-scope="scope">
          <!-- 行内显示图片 -->
          <img v-if="column.imgFlag==true"
               :src=" scope.row[column.prop].indexOf('http') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) "
               width="60" height="60" class="img"/>
          <!-- 行内显示开关按钮 -->
          <el-switch v-else-if="column.switchFlag==true" v-model="scope.row[column.prop]" :active-value="1"
                     :inactive-value="0" disabled/>
          <!-- 行内显示tag标签 -->
          <span v-else-if="column.tagFlag==true">
                        <span v-for="item in column.tagFormatter" :key="item.value">
                            <el-tag v-if="item.value==scope.row[column.prop]" :type="item.type">{{ item.text }}</el-tag>
                        </span>
                    </span>
          <!-- 行内格式自定义 -->
          <span v-else-if="column.formatter"> {{ column.formatter(scope.row) }}</span>
          <!--默认显示文本-->
          <span v-else>{{ scope.row[column.prop] }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="240" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" class="el-button--primary" @click="handleUpdate(scope.row, 2)"> 编辑
          </el-button>
          <el-button type="text" icon="el-icon-delete" class="el-button--danger" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格-页脚区域 -->
    <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="pageRequest.pageNum"
                :limit.sync="pageRequest.pageSize" @pagination="getList"/>

    <!--   文件导入-->
    <el-dialog title="导入" width="30%" top="5vh" :visible.sync="dialogImportVisible"
               :close-on-click-modal="false">
      <el-upload
          class="upload-demo"
          drag
          v-model="importFile"
          :action="CMBASE.baseUploadExcelAction"
          multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="closeImportDialog()">关闭</el-button>
      </div>
    </el-dialog>

    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="80%" top="5vh" :visible.sync="dialogFormVisible"
               @close="closeDialog()">
      <el-form :model="dataForm" label-width="140px" :rules="dataFormRules" ref="dataForm" style="width: 80%">

        <el-form-item label="题型" prop="questionType">
          <el-select v-model="dataForm.questionType" placeholder="请选择题型">
            <el-option label="单选题" :value="1"></el-option>
            <el-option label="多选题" :value="2"></el-option>
            <el-option label="判断题" :value="3"></el-option>
            <el-option label="填空题" :value="4"></el-option>
            <el-option label="实践题" :value="6"></el-option>
          </el-select>
<!--          <span style="padding-left: 20px ;color: red ;font-size: small" v-if="dataForm.questionType===1"> 选择题的答案填ABCD选项序号 </span>-->
<!--          <span style="padding-left: 20px ;color: red ;font-size: small" v-if="dataForm.questionType===2"> 多选题的答案用英文,分割 </span>-->
<!--          <span style="padding-left: 20px ;color: red ;font-size: small" v-if="dataForm.questionType===3"> 判断题的答案填写正确选项 例如：A选项内容 </span>-->
<!--          <span style="padding-left: 20px ;color: red ;font-size: small" v-if="dataForm.questionType===4"> 填空题题目中的答案数量需要自行定义；多个空格的答案用“|”分隔，同一个空格有同义词答案，用英文分号“;"分隔；题目中的填空符数量要与答案数量一致 </span>-->
<!--          <span style="padding-left: 20px ;color: red ;font-size: small" v-if="dataForm.questionType===6"> 主观题若无标准答案，可填写评分标准方便阅卷人打分 </span>-->
        </el-form-item>
        <el-form-item label="科目名称" prop="levelName">
          <el-select v-model="dataForm.subjectId">
            <el-option v-for="item in subjectList" :label="item.levelName" :key="item.id" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="难度系数" prop="difficult">
          <el-select v-model="dataForm.difficult" placeholder="请选择难度系数">
            <el-option label="1分" :value="1"></el-option>
            <el-option label="2分" :value="2"></el-option>
            <el-option label="3分️" :value="3"></el-option>
            <el-option label="4分" :value="4"></el-option>
            <el-option label="5分" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择题库" prop="baseId">
          <el-select v-model="dataForm.baseId" placeholder="请选择题库">
            <el-option v-for="item in baseList" :key="item.id" :value="item.id" :label="item.baseName" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题目总分" prop="score">
          <el-input-number v-model="dataForm.score" :min="1" :max="1000" label="题目总分"></el-input-number>
        </el-form-item>



        <el-form-item label="题目内容" prop="title">
          <el-input :rows="3" autosize type="textarea" v-model="dataForm.title"></el-input>
          <el-button v-if="dataForm.questionType === 4" type="success" @click="titleBlankAdd">添加填空</el-button>
          <el-button v-if="dataForm.questionType === 4" type="info" @click="titleBlankRemove">删除填空</el-button>
        </el-form-item>
        <el-form-item label="题目内容图片" prop="images">
          <CmUpload v-model="dataForm.images"></CmUpload>
        </el-form-item>
        <el-form-item v-if="dataForm.questionType === 1 || dataForm.questionType === 2" label="答案选项" prop="correct">
          <el-form-item :label="item.prefix" :key="item.prefix" v-for="(item,index) in items" label-width="50px"
                        class="question-item-label displays">
            <el-input v-model="item.prefix" style="width:50px;"/>
            <el-input v-model="item.content" class="question-item-content-input"/>
            <el-button type="danger" size="mini" class="question-item-remove" icon="el-icon-delete"
                       @click="questionItemRemove(index)"></el-button>
          </el-form-item>
        </el-form-item>
        <el-form-item v-if="dataForm.questionType === 3" label="答案选项" prop="correct">
          <el-form-item :label="item.prefix" :key="item.prefix" v-for="item in tureFalseItems" label-width="50px"
                        class="question-item-label displays">
            <el-input v-model="item.prefix" style="width:50px;"/>
            <el-input v-model="item.content" class="question-item-content-input"/>
          </el-form-item>
        </el-form-item>
        <el-form-item v-if="dataForm.questionType === 1" label="标准答案" prop="correct">
          <el-radio-group v-model="dataForm.correct">
            <el-radio v-for="item in items" :key="item.prefix" :label="item.prefix">{{ item.prefix }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="dataForm.questionType === 2" label="标准答案" prop="correctArray">
          <el-checkbox-group v-model="dataForm.correctArray" @change="clearCorrectArray()" ref="correctArray">
            <el-checkbox v-for="item in items" :label="item.prefix" :key="item.prefix">{{ item.prefix }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item v-if="dataForm.questionType === 3" label="标准答案" prop="correct">
          <el-radio-group v-model="dataForm.correct">
            <el-radio v-for="item in tureFalseItems" :key="item.prefix" :label="item.prefix">{{ item.prefix }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="dataForm.questionType === 4" label="标准答案" prop="correct">
          <el-form-item :label="item.prefix" :key="item.prefix" v-for="(item, index) in blankItems" label-width="50px"
                        class="question-item-label displays">
            <el-input v-model="item.content" class="question-item-content-input"/>
            <el-button type="danger" size="mini" class="question-item-remove" icon="el-icon-delete"
                       @click="blankItemRemove(index)"></el-button>
          </el-form-item>
        </el-form-item>
        <el-form-item label="解析" prop="analyze">
          <tinymce :height="300" v-model="dataForm.analyze" id='tinymce' :value="dataForm.analyze"
                   v-if="dialogFormVisible && dataForm.analyze"></tinymce>
        </el-form-item>
        <el-form-item label="试题排序" prop="orderNo">
          <el-input-number v-model="dataForm.orderNo" :min="1"  label="试题排序"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="dataForm.questionType === 1 || dataForm.questionType === 2" type="success"
                   @click="questionItemAdd">添加选项
        </el-button>
        <el-button size="mini" @click.native="closeDialog()">取消</el-button>
        <el-button size="mini" @click.native="saveFormData()" :loading="editLoading" type="primary">提交</el-button>
      </div>
    </el-dialog>


  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 分页栏信息
import Tinymce from '@/components/CmUEditor'
import CmUpload from '@/components/CmUpload' // 上传图片组件引入
export default {
  name: 'question',
  components: {
    Pagination,
    Tinymce,
    CmUpload,
  },
  directives: {},
  filters: {},
  data() {
    return {
      importFile: {},
      tableKey: 0,
      tableList: [],//表格数据源
      subjectList: [],//表格数据源
      levelNameOption: [],//表格数据源
      tableTotal: 0,//表格总条数数据
      listLoading: true,
      pageRequest: {pageNum: 1, pageSize: 10,},
      searchParam: {},
      orderParam: {order_no: true},
      dialogFormVisible: false,//默认不显示弹出框
      dialogImportVisible: false,//默认不显示弹出框
      operation: true, // true:新增, false:编辑
      editLoading: false,//保存表单时loading框
      columns: [
        {prop: 'content', label: '题目部分内容', sortable: false},
        {prop: 'levelName', label: '科目名称', sortable: false},
        {prop: 'baseName', label: '题库名称', sortable: false},
        {
          prop: 'questionType', label: '题型', sortable: false, tagFlag: true,
          tagFormatter: [
            {text: '单选题', value: 1, type: 'success'},
            {text: '多选题', value: 2, type: 'success'},
            {text: '判断题', value: 3, type: 'success'},
            {text: '填空题', value: 4, type: 'success'},
            // {text: '简答题', value: 5, type: 'success'},
            {text: '实践题', value: 6, type: 'success'}
          ]
        },
        {
          prop: 'difficult', label: '难度系数', sortable: false, tagFlag: true,
          tagFormatter: [
            {text: '1分', value: 1, type: 'primary'},
            {text: '2分', value: 2, type: 'primary'},
            {text: '3分', value: 3, type: 'success'},
            {text: '4分', value: 4, type: 'success'},
            {text: '5分', value: 5, type: 'danger'},
          ]
        },
        {prop: 'score', label: '题目总分', sortable: false},
        {prop: 'orderNo', label: '试题排序', sortable: false},
        {prop: 'createTime', label: '创建时间', sortable: false}
      ],
      fileList: [],
      // 新增编辑界面数据
      dataForm: {},
      //表单检验规则
      dataFormRules: {},
      items: [
        {prefix: 'A', content: ''},
        {prefix: 'B', content: ''},
        {prefix: 'C', content: ''},
        {prefix: 'D', content: ''}
      ],
      blankItems: [],
      tureFalseItems: [
        {prefix: 'A', content: '是'},
        {prefix: 'B', content: '否'},
      ],
      baseList:[],
    }
  },
  created() {
    this.pageRequest.orderParam = this.orderParam
    this.getList();
    this.getSubjectList();
    this.getBaseOptions();
  },
  methods: {
    getSubjectList() {
      //【API请求】----获取表格列表数据
      this.$api.getSSubjectList().then(response => {
        this.subjectList = response.data.content
      }).catch((res) => {
        this.$message({message: '列表获取失败', type: 'error'})
      })
    },
    handleImport() {
      this.dialogImportVisible = true;
    },
    handleExport() {
      this.$confirm('是否确定导出模板？', '提示', {}).then(() => {
        window.open(this.CMBASE.baseFileContext + "/CM-API/api/export/exportQuestions")
      }).catch()
    },
    closeImportDialog() {
      this.dialogImportVisible = false;
      this.getList()
    },
    //获取表格数据
    getList() {
      this.listLoading = true
      //【API请求】----获取表格列表数据
      this.$api.getVQuestionsList(this.pageRequest).then(response => {
        this.tableList = response.data.content
        this.tableTotal = response.data.total
        this.listLoading = false;
      }).catch((res) => {
        this.$message({message: '列表获取失败', type: 'error'})
      })
    },
    //表格数据筛选
    handleFilter() {
        this.pageRequest = {
            pageNum: 1,
            pageSize: 10,
        }
      this.pageRequest.orderParam = this.orderParam
      this.pageRequest.searchParam = this.searchParam
      console.log(this.subjectList)
      this.getList()
    },
    //【按钮点击】--- 弹出新增表单
    handleCreate() {
      this.operation = true;
      this.initDataForm();
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false;
      })

    },
    //【按钮点击】--- 弹出编辑表单
    handleUpdate(row) {
      this.operation = false;
      this.$api.sQuestionsInfo({id: row.id}).then(response => {
        console.log(response.data , "data")
        this.dataForm = response.data
        switch (row.questionType) {
          case 1:
          case 2:
            this.items = this.dataForm.items
            break;
          case 3:
            this.tureFalseItems = this.dataForm.items
            break;
          case 4:
            console.log(this.dataForm.correctArray, 'this.dataForm.correctArray')
            this.dataForm.correctArray.forEach(
                (value, index) => {
                  let vm = {
                    prefix: (index + 1) + "",
                    content: value
                  };
                  this.blankItems.push(vm)
                }
            )
            console.log(this.blankItems, 'this.blankItems')
            break;
          default:
        }
      }).catch((res) => {
        this.$message({message: '详情获取失败', type: 'error'})
      })
      // this.dataForm = Object.assign({}, row)
      //显示编辑菜单
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false;
      })
    },
    //保存表单数据
    saveFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false;
        }
        const dataForm = this.dataForm;
        switch (dataForm.questionType) {
          case 1:
          case 2:
            this.dataForm.items = this.items
            break;
          case 3:
            this.dataForm.items = this.tureFalseItems
            break;
          case 4:
            console.log(this.blankitems,"this.blankItem")
            this.dataForm.correctArray=[]
            this.blankItems.forEach(
                element => this.dataForm.correctArray.push(element.content)
            )
            break;
          default:
        }
        console.log(dataForm,"dataForm");
        this.editLoading = true;
        // 【API请求】----保存数据
        this.$api.saveSQuestions({
          params: JSON.stringify(dataForm)
        }).then(() => {
          this.editLoading = false;//关闭loading框
          this.dialogFormVisible = false;//关闭表单页面
          this.initDataForm();//重置表单数据
          this.getList();//重新获取表格数据
          this.$notify({title: '成功', message: '保存成功', type: 'success', duration: 2000})
        }).catch(() => {
          this.editLoading = false;//关闭loading框
          this.$message({message: '操作失败', type: 'error'})
        });
      })
    },
    //【按钮点击】---删除行
    handleDelete(row) {
      this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
        //【API请求】---- 删除数据
        this.$api.deleteSQuestions({ids: row.id}).then(() => {
          this.$message({message: '操作成功', type: 'success'})
            this.pageRequest.pageNum = 1
          this.getList();
        })
      }).catch(() => {
        this.$message({message: '操作失败', type: 'error'})
      });
    },
    questionItemAdd() {
      let items = this.items
      let newLastPrefix
      if (items.length > 0) {
        let last = items[items.length - 1]
        newLastPrefix = String.fromCharCode(last.prefix.charCodeAt() + 1)
      } else {
        newLastPrefix = 'A'
      }
      items.push({id: null, prefix: newLastPrefix, content: ''})
    },
    titleBlankAdd() {
      let items = this.blankItems
      let newLastPrefix
      if (items.length > 0) {
        let last = items[items.length - 1]
        newLastPrefix = (Number(last.prefix) + 1) + ""
      } else {
        newLastPrefix = '1'
      }
      items.push({id: null, prefix: newLastPrefix, content: ''})
      this.dataForm.title = this.dataForm.title + newLastPrefix + ".____"
    },

    //获取题库列表
    getBaseOptions(){
      const pageParam = {pageNum: 1, pageSize: 999}
      this.$api.getSQuestionBaseList(pageParam).then(res=>{
        this.baseList = res.data.content
      })
    },

    titleBlankRemove() {
      let items = this.blankItems;
      items.splice(items.length - 1, 1)
      let title = this.dataForm.title;
      this.dataForm.title = title.substring(0, title.length - 6)
    },
    questionItemRemove(index) {
      this.items.splice(index, 1)
    },
    blankItemRemove(index) {
      let title = this.dataForm.title;
      let quesName = (this.blankItems[index].prefix) + '.____'
      let position = title.indexOf(quesName)
      let end = quesName.length
      this.blankItems.splice(index, 1)
      this.dataForm.title = title.substring(0, position) + title.substring(position + end, title.length)
    },
    //初始化表单数据，重新渲染
    initDataForm() {
      this.dataForm = {
        questionType: '',
        baseId:'',
        title: '',
        images: '',
        subjectId: '',
        items: '',
        analyze: '解析',
        score: '',
        correct: '',
        correctArray: [],
        difficult: '',
        id: '',
        orderNo: 0,
      };
      this.items = [
        {prefix: 'A', content: ''},
        {prefix: 'B', content: ''},
        {prefix: 'C', content: ''},
        {prefix: 'D', content: ''}
      ];
      this.blankItems = [];
      this.tureFalseItems = [
        {prefix: 'A', content: '是'},
        {prefix: 'B', content: '否'},
      ];
    },
    //关闭表单弹出框
    closeDialog() {
      this.initDataForm();
      this.$refs['dataForm'].resetFields();
      this.dialogFormVisible = false
    },

    clearCorrectArray(){
      this.$refs['correctArray'].resetFields();
    },

  }


}
</script>
